package test;

public class Solution1 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
    }

    public ListNode insertionSortList(ListNode head) {
        ListNode node = null;

        while (head != null) {
            ListNode newNode = new ListNode(head.val);
            if (node == null) {
                node = newNode;
                head = head.next;
                continue;
            }

            ListNode cur = node;
            ListNode pre = null;

            while(cur != null && cur.val <= head.val) {
                pre = cur;
                cur = cur.next;
            }

            newNode.next = cur;
            if(pre != null) {
                pre.next = newNode;
            } else {
                node = newNode;
            }

            head = head.next;
        }

        return node;
    }

    public static void main(String[] args) {
        Solution1 s = new Solution1();
        ListNode head = new ListNode(4);
        head.next = new ListNode(6);
        head.next.next = new ListNode(5);
        head.next.next.next = new ListNode(3);

        ListNode c = s.insertionSortList(head);

        while(c != null) {
            System.out.print(c.val + "->");
            c = c.next;
        }
    }
}
